#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/sys/printk.h>
#include <zephyr/logging/log.h>
#include <zephyr/devicetree.h>

#include "led.h"

LOG_MODULE_REGISTER(gpio_led, LOG_LEVEL_INF);

static struct gpio_dt_spec led = GPIO_DT_SPEC_GET(DT_NODELABEL(ready_led), gpios);
static int led_mode = LED_MODE_SOLID_OFF; // 默认模式为常关

// 定时器用于LED闪烁
static struct k_timer led_timer;

// 定时器回调函数
static void led_timer_handler(struct k_timer *dummy)
{
    static bool led_on = false;

    if (led_mode == LED_MODE_SLOW_BLINK)
    {
        gpio_pin_set_dt(&led, led_on);
        led_on = !led_on;
    }
    else if (led_mode == LED_MODE_FAST_BLINK)
    {
        gpio_pin_set_dt(&led, led_on);
        led_on = !led_on;
    }
}

// LED 控制函数
static int gpio_led_init(void)
{
    if (!gpio_is_ready_dt(&led))
    {
        LOG_ERR("LEDx GPIO module is not ready.");
        return -ENODEV;
    }

    // 使用 gpio_pin_configure_dt 来配置 GPIO 引脚
    int ret = gpio_pin_configure_dt(&led, GPIO_OUTPUT_ACTIVE);
    if (ret < 0)
    {
        LOG_ERR("Failed to configure GPIO pin");
    }

    // 初始化定时器，闪烁周期为默认快闪
    k_timer_init(&led_timer, led_timer_handler, NULL);

    return 0;
}

void gpio_led_set_mode(int mode)
{
    // 如果当前模式是闪烁模式，先停止定时器
    if (led_mode == LED_MODE_SLOW_BLINK || led_mode == LED_MODE_FAST_BLINK)
    {
        k_timer_stop(&led_timer); // 停止定时器
    }

    led_mode = mode;

    switch (led_mode)
    {
    case LED_MODE_SOLID_ON:
        gpio_pin_set_dt(&led, 1);
        break;
    case LED_MODE_SOLID_OFF:
        gpio_pin_set_dt(&led, 0);
        break;
    case LED_MODE_SLOW_BLINK:
        k_timer_start(&led_timer, K_SECONDS(1), K_SECONDS(1)); // 每秒闪烁
        break;
    case LED_MODE_FAST_BLINK:
        k_timer_start(&led_timer, K_MSEC(100), K_MSEC(100)); // 每100毫秒闪烁
        break;
    default:
        break;
    }
}

// 初始化时调用，设置默认模式
SYS_INIT(gpio_led_init, APPLICATION, 90);
